//
//  ComicViewController.m
//  SweetComics
//
//  Created by dlios on 15-1-31.
//  Copyright (c) 2015年 LeeZhe. All rights reserved.
//

#import "ComicViewController.h"

#import "PictureList.h"
#import "AFHTTPRequestOperationManager.h"
#import "UIImageView+WebCache.h"
#import "DataBaseHandler.h"
#import "MBProgressHUD.h"
#import "HomePageViewController.h"
@interface ComicViewController ()<UIScrollViewDelegate, UIActionSheetDelegate,UIAlertViewDelegate,UIActionSheetDelegate>

@property (nonatomic, retain) UIScrollView *scrollView;
@property (nonatomic, retain) NSMutableArray *arr;
@property (nonatomic, retain) DataBaseHandler *dbHandler;
@property (nonatomic,retain)  MBProgressHUD *mbView;
@end


@implementation ComicViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"beijing.jpg"]];
    [self createView];
    
    // Do any additional setup after loading the view.
    self.navigationController.navigationBarHidden = YES;
    [self setupData];
    [self addObserver:self forKeyPath:@"arr" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:@"suibian"];
    
    
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (self.arr) {
        [_mbView removeFromSuperview];
        
    }
}
- (void)createView
{
    self.mbView = [[[MBProgressHUD alloc] initWithView:self.view] autorelease];
    [_mbView show:YES];
    _mbView.labelFont = [UIFont systemFontOfSize:11];
    _mbView.labelText = @"努力加载中";
    [self.view addSubview:_mbView];
    
}

- (void)setupData
{
    self.arr = [NSMutableArray array];
    self.scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    self.scrollView.delegate = self;
    //  创建 阅读漫画界面 请求数据 给每个漫画的 View 赋值;
    
    NSString *str = [NSString stringWithFormat: @"http://mobilev3.ac.qq.com/Comic/chapterPictureListForIos/comic_id/%@/cid/%ld/clientType/0", self.comic.comic_id, (long)self.i];
    //    NSLog(@"%@", str);
    [self.dbHandler glanceComic:self.comic number:self.i count:1];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        //        [self.dbHandler glanceComic:self.comic number:self.i count:0];
        NSDictionary *dic = responseObject;
        NSMutableArray *temp = [[dic objectForKey:@"data"]objectForKey:@"img_infos"];
        if (temp) {
            for (NSDictionary *dic1 in temp)
            {
                PictureList *pic = [[PictureList alloc] init];
                [pic setValuesForKeysWithDictionary:dic1];
                [self.arr addObject:pic];
                [pic release];
                _scrollView.backgroundColor = [UIColor blackColor];
                _scrollView.pagingEnabled = YES;
                [self.view addSubview:self.scrollView];
                for (NSInteger m = 0; m < self.arr.count; m++) {
                    _scrollView.contentSize = CGSizeMake(self.view.frame.size.width * self.arr.count + 1, 0);
                    UIImageView  *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width * m, 40, self.view.frame.size.width, self.view.frame.size.height - 80)];
                    imageView.backgroundColor  =  [UIColor colorWithPatternImage:[UIImage imageNamed:@"beijing.jpg"]];
                    [self.scrollView addSubview:imageView];
                    PictureList *pic = [[PictureList alloc] init];
                    pic = [self.arr objectAtIndex:m];
                    
                    NSURL *url = [NSURL URLWithString:pic.current_img_url];
                    [imageView setImageWithURL:url];
                    // 上一页
                    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeSystem];
                    leftButton.frame = CGRectMake(self.view.frame.size.width * m, 40, self.view.frame.size.width / 2, self.view.frame.size.height - 80);
                    //                leftButton.backgroundColor = [UIColor yellowColor];
                    [leftButton setTitle:@"" forState:UIControlStateNormal];
                    [self.scrollView addSubview:leftButton];
                    [leftButton addTarget:self action:@selector(leftButton:) forControlEvents:UIControlEventTouchUpInside];
                    // 下一页
                    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeSystem];
                    rightButton.frame = CGRectMake(self.view.frame.size.width / 2 + self.view.frame.size.width * m, 40, self.view.frame.size.width / 2, self.view.frame.size.height - 80);
                    //                rightButton.backgroundColor = [UIColor blueColor];
                    [self.scrollView addSubview:rightButton];
                    [rightButton setTitle:@"" forState:UIControlStateNormal];
                    [rightButton addTarget:self action:@selector(rightButton:) forControlEvents:UIControlEventTouchUpInside];
                    // 菜单
                    UIButton *centerButton = [UIButton buttonWithType:UIButtonTypeSystem];
                    centerButton.frame = CGRectMake(self.view.frame.size.width / 4 + (self.view.frame.size.width / 2 + self.view.frame.size.width / 2) * m, (self.view.frame.size.height  - 80) / 4 + 40, self.view.frame.size.width / 2, (self.view.frame.size.height  - 80) / 2);
                    //                centerButton.backgroundColor = [UIColor redColor];
                    [centerButton setTitle:@"" forState:UIControlStateNormal];
                    [self.scrollView addSubview:centerButton];
                    
                    [centerButton addTarget:self action:@selector(centerButton:) forControlEvents:UIControlEventTouchUpInside];
                }
            }
        }
        else
        {
            self.navigationController.navigationBarHidden = NO;
            UIAlertView *alterView = [[[UIAlertView alloc] initWithTitle:@"甜心提示" message:@"漫画偷懒啦\r返回首页吧" delegate: self cancelButtonTitle:@"好的" otherButtonTitles: nil] autorelease];
            [alterView show];
            [self.view addSubview:alterView];
            
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"甜心提示" delegate: self cancelButtonTitle:@"有网络继续阅读" destructiveButtonTitle:@"好像没有请求到漫画哦\r检查下网络把" otherButtonTitles:nil];
        [actionSheet showInView:self.view];
        [actionSheet release];
        [self.view addSubview:actionSheet];
        [_mbView hide:YES];
        
    }];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [self setupData];
    }
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)leftButton:(UIButton *)button
{
    NSInteger page = _scrollView.contentOffset.x / self.view.frame.size.width;
    NSInteger count = _scrollView.contentSize.width / self.view.frame.size.width;
    if ((self.i == 1 ) && (self.scrollView.contentOffset.x == 0))
    {
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"已经是第一话了哦" delegate: self cancelButtonTitle:@"好的" destructiveButtonTitle:@"点击屏幕右侧切换下一页" otherButtonTitles:nil];
        [actionSheet showInView:self.view];
        [self.view addSubview:actionSheet];
    }
    else
    {
        if(self.scrollView.contentOffset.x == 0)
        {
            self.i = self.i - 1;
            self.title = [NSString stringWithFormat:@"第%ld话", (long)self.i];
            [self.view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
            [self  setupData];
            self.hidesBottomBarWhenPushed = YES;
            NSLog(@"当前已是第一页");
        }else
        {
            
            self.scrollView.contentOffset = CGPointMake(self.scrollView.contentOffset.x - self.view.frame.size.width, 0);
            
            self.title = [NSString stringWithFormat:@"第%ld话/(%ld / %ld)", (long)self.i, page ,count];
        }
    }
}
- (void)rightButton:(UIButton *)button
{
    NSInteger page = _scrollView.contentOffset.x / self.view.frame.size.width;
    NSInteger count = _scrollView.contentSize.width / self.view.frame.size.width;
    if ((self.i == [self.comic.lated_seqno integerValue]) && ((self.scrollView.contentOffset.x + self.view.frame.size.width) == self.view.frame.size.width * self.arr.count))
    {
        UIActionSheet *actionSheet = [[[UIActionSheet alloc] initWithTitle:@"暂无后续更新哦，亲！" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"确定" otherButtonTitles:nil] autorelease];
        [actionSheet showInView:self.view];
        [self.view addSubview:actionSheet];
        NSLog(@"暂无后续更新");
    }
    else
    {
        if((self.scrollView.contentOffset.x + self.view.frame.size.width) == (self.view.frame.size.width * self.arr.count))
        {
            self.i = self.i + 1;
            
            
            self.title = [NSString stringWithFormat:@"第%ld话", (long)self.i];
            [self.view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
            [self  setupData];
            self.hidesBottomBarWhenPushed = YES;
            NSLog(@"当前已是最后一页");
        }else
        {
            self.scrollView.contentOffset = CGPointMake(self.scrollView.contentOffset.x + self.view.frame.size.width, 0);
            self.title = [NSString stringWithFormat:@"第%ld话/(%ld / %ld)", (long)self.i, page + 2,count];
        }
    }
}



- (void)centerButton:(UIButton *)button
{
    NSInteger page = _scrollView.contentOffset.x / self.view.frame.size.width;
    NSInteger count = _scrollView.contentSize.width / self.view.frame.size.width;
    if (self.flag) {
        
        
        self.title = [NSString stringWithFormat:@"第%ld话/(%ld / %ld)", (long)self.i, page + 1,count];
        self.navigationController.navigationBarHidden = YES;
    }else
    {
        self.title = [NSString stringWithFormat:@"第%ld话/(%ld / %ld)", (long)self.i,page + 1,count];
        self.navigationController.navigationBarHidden = NO;
    }
    self.flag = !self.flag;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // 当scrollView滚动的时候, 就会调用这个方法
    // 1. 通过偏移量计算当前的页数
    
    NSInteger page = _scrollView.contentOffset.x / self.view.frame.size.width;
    NSInteger count = _scrollView.contentSize.width / self.view.frame.size.width;
    
    
    
    if (self.scrollView.contentOffset.x + self.view.frame.size.width == self.arr.count * self.view.frame.size.width + 1) {
        
        NSLog(@"%ld",page);
        
        self.i = self.i + 1;
        
        [self.view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        [self  setupData];
        //        self.hidesBottomBarWhenPushed = YES;
        //        NSLog(@"!!!!! %ld",self.arr.count);
        self.title = [NSString stringWithFormat:@"第%ld话",self.i];
    }else
        
    {
        self.title = [NSString stringWithFormat:@"第%ld话/(%ld / %ld)", (long)self.i, page + 1,count];
    }
    
    
    
    
    
    //    self.title = [NSString stringWithFormat:@"第%ld话/第%ld页", (long)self.i, (long)page + 1];
    
    
}



- (void)dealloc
{
    [_imageView release];
    [_comic release];
    [_dbHandler release];
    [self removeObserver:self forKeyPath:@"arr"];
    [super dealloc];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
